import { CalendarDay, Festival, MarketingTemplate } from '../types/calendar';
import axios from 'axios';
import { Lunar } from 'lunar-javascript';

// 配置axios基础URL和选项
const api = axios.create({
  baseURL: 'http://localhost:8080',
  timeout: 5000,
  headers: {
    'Content-Type': 'application/json'
  }
});

// 添加响应拦截器用于调试
api.interceptors.response.use(
  response => response,
  error => {
    console.error('API Error:', {
      url: error.config?.url,
      method: error.config?.method,
      params: error.config?.params,
      status: error.response?.status,
      message: error.message
    });
    return Promise.reject(error);
  }
);

// 获取某月的所有日期
export const getMonthDays = (year: number, month: number): CalendarDay[] => {
  const firstDay = new Date(year, month, 1);
  const lastDay = new Date(year, month + 1, 0);
  
  const days: CalendarDay[] = [];
  
  // 添加上月的日期
  const firstDayWeek = firstDay.getDay();
  for (let i = firstDayWeek - 1; i >= 0; i--) {
    const date = new Date(year, month, -i);
    days.push({
      date,
      day: date.getDate(),
      month: date.getMonth(),
      year: date.getFullYear(),
      isCurrentMonth: false,
      festivals: [],
      lunarDate: getLunarDate(date)
    });
  }
  
  // 添加本月的日期
  for (let i = 1; i <= lastDay.getDate(); i++) {
    const date = new Date(year, month, i);
    days.push({
      date,
      day: i,
      month,
      year,
      isCurrentMonth: true,
      festivals: [],
      lunarDate: getLunarDate(date)
    });
  }
  
  // 添加下月的日期
  const remainingDays = 42 - days.length; // 保证日历显示6行
  for (let i = 1; i <= remainingDays; i++) {
    const date = new Date(year, month + 1, i);
    days.push({
      date,
      day: date.getDate(),
      month: date.getMonth(),
      year: date.getFullYear(),
      isCurrentMonth: false,
      festivals: [],
      lunarDate: getLunarDate(date)
    });
  }
  
  return days;
};

// 获取农历日期
export const getLunarDate = (date: Date): string => {
  const lunar = Lunar.fromDate(date);
  return lunar.getDayInChinese();
};

// 获取节日信息
export const getFestivals = async (year: number, month: number): Promise<Festival[]> => {
  try {
    console.log(`Fetching festivals for ${year}-${month + 1}`);
    const response = await api.get('/api/festivals', {
      params: {
        year,
        month: month + 1
      }
    });
    console.log('Festivals response:', response.data);
    return response.data;
  } catch (error) {
    console.error('获取节日信息失败:', error);
    return [];
  }
};

// 获取营销模板信息
// 导出一个异步函数，用于获取营销模板信息
export const getMarketingTemplates = async (): Promise<MarketingTemplate[]> => {
  try {
    // 发送GET请求，获取营销模板信息
    const response = await api.get('/api/marketing-templates');
    // 返回获取到的数据
    return response.data;
  } catch (error) {
    // 如果发生错误，打印错误信息，并返回空数组
    console.error('获取营销模板信息失败:', error);
    return [];
  }
};

// 格式化日期
// 导出一个函数，用于格式化日期
export const formatDate = (date: Date): string => {
  // 将日期转换为ISO字符串，并使用split方法将其分割为日期和时间的部分
  return date.toISOString().split('T')[0];
};

// 计算剩余天数
export const getDaysLeft = (targetDate: string): number => {
  const target = new Date(targetDate);
  const today = new Date();
  const diffTime = target.getTime() - today.getTime();
  return Math.ceil(diffTime / (1000 * 60 * 60 * 24));
}; 